using Microsoft.AspNetCore.Mvc;
using mozhi.smarterp.AuthorCenter.Users;
using System;
using System.Threading.Tasks;
using Volo.Abp.AspNetCore.Mvc.UI.RazorPages;
using Volo.Abp.Identity;
using Volo.Abp.Identity.AspNetCore;

namespace mozhi.smarterp.AuthorCenter.Pages.Account
{
    public class LinkLoginModel : AbpPageModel
    {
        [HiddenInput]
        [BindProperty(SupportsGet = true)]
        public string ReturnUrl { get; set; }

        [HiddenInput]
        [BindProperty(SupportsGet = true)]
        public string ReturnUrlHash { get; set; }

        [HiddenInput]
        [BindProperty(SupportsGet = true)]
        public Guid SourceLinkUserId { get; set; }

        [HiddenInput]
        [BindProperty(SupportsGet = true)]
        public Guid? SourceLinkTenantId { get; set; }

        [HiddenInput]
        [BindProperty(SupportsGet = true)]
        public string SourceLinkToken { get; set; }

        [HiddenInput]
        [BindProperty(SupportsGet = true)]
        public Guid TargetLinkUserId { get; set; }

        [HiddenInput]
        [BindProperty(SupportsGet = true)]
        public Guid? TargetLinkTenantId { get; set; }

        protected IdentityUserManager UserManager { get; }

        private readonly IUserTenantAppService UserTenantAppService;

        protected AbpSignInManager SignInManager { get; }

        public LinkLoginModel(IdentityUserManager userManager, IUserTenantAppService userTenantAppService , AbpSignInManager signInManager)
        {
            UserManager = userManager;
            UserTenantAppService = userTenantAppService;
            SignInManager = signInManager;
        }

        public async Task<ActionResult> OnGetAsync()
        {
            return Page();
        }


        public async Task<IActionResult> OnPostAsync()
        {
            var linkValidate = await UserTenantAppService.VerifyUserTenantLoginTokenAsync(TargetLinkUserId.ToString() , TargetLinkTenantId , SourceLinkToken);

            if (!linkValidate)
            {
                return Redirect("/Account/Login");
            }

            using (CurrentTenant.Change(TargetLinkTenantId))
            {
                var user = await UserManager.FindByIdAsync(TargetLinkUserId.ToString());

                await UserManager.UpdateSecurityStampAsync(user);

                await SignInManager.SignInAsync(user, isPersistent: false);

                var returnUrl = ReturnUrl + (ReturnUrl.IndexOf("?") > -1 ? "&tenantId=" + TargetLinkTenantId : "?tenantId=" + TargetLinkTenantId);

                return Redirect(returnUrl);
            }
        }
    }
}
